

public class GameLogic implements IGameLogic {
	private int x = 0;
	private int y = 0;
	private int playerID;
	private GameBoard gameBoard;
	private GameBoardTool gTool = new GameBoardTool();
	private int won = 0;
	private int[] columnOrder;
	public GameLogic() {
		//TODO Write your implementation for this method
	}

	public void initializeGame(int x, int y, int playerID) {
		this.x = x;
		this.y = y;
		this.playerID = playerID; 
		gameBoard = new GameBoard(x, y);
		columnOrder = new int[x];
		setColumnOrder();

	}

	public Winner gameFinished() {

		if (won == 1) return Winner.PLAYER1;
		if (won == 2) return Winner.PLAYER2;
		if (!gameBoard.isFull()) return Winner.NOT_FINISHED;
		else return Winner.TIE;
	}


	public void insertCoin(int column, int playerID) {

		column++;

		if (won == 0 && gTool.isWinningColumn(gameBoard, column, playerID)) won = playerID;

		gameBoard.insertInColumn(column, playerID);

	}

	public int decideNextMove() {

		//TODO MiniMax()
		/*
		 * use peakColumn(column, player) which returns a cloned gameboard
		 * and columnValue() for recursion
		 * 
		 * 
		 * 
		 */


		// Temporary method...
		// find best valued column
		int bestMove = 0;
		double best = 0;
		double value;

		// check if player has winning option or must and defend
		for (int i = 1; i <= columnOrder.length; i++) {
			//defend
			if (!gTool.columnFull(gameBoard, i) && gTool.isWinningColumn(gameBoard, i, otherPlayer(playerID))){
				System.out.println("Defend! " + (i-1));
				return i-1;
			}
			// winning move
			if (!gTool.columnFull(gameBoard, i) && gTool.isWinningColumn(gameBoard, i, (playerID))) {
				System.out.println("Win it! " + (i-1));
				return i-1;
			}
		}

		// find best columnValue
		for (int i = 1; i <= columnOrder.length; i++) {
			value = gTool.columnValue(gameBoard, i, playerID, 1);
			System.out.println("Value of " + i + " " + value);
			
			// set best value
			if (playerID == 1 && value < best || playerID == 2 && value > best ) {
				best = value;	
				bestMove = i-1;
			}	
			
		}


		// Call MiniMax
		 Minimax mm = new Minimax(gameBoard, playerID);
		 bestMove = mm.getAction();
		 mm = null;

		System.out.println("=======================\nBest Move = " + bestMove + "\n===========================");
		return bestMove;

	}

	// returns opponent
	private int otherPlayer (int player) {
		if (player == 1) return 2;
		else return 1;
	}

	private void setColumnOrder() {	
		for (int i = 0; i < this.x; i++) {
			columnOrder[i] = i;	
		}
	}


}
